package com.zzy.study.socketANDnio;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class BasicSocketClient {

	private static final int prot = 9111;
	private Socket socket;
	private InputStream in = null;
	private OutputStream out = null;
	private static byte[] buffer = "hellffffffffffochina".getBytes();
	
	public static void main(String[] args) throws InterruptedException {
		new BasicSocketClient().send();
	}
	
	public BasicSocketClient() {
		try {
			socket = new Socket("localhost", prot);
			in = socket.getInputStream();
			out = socket.getOutputStream();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void send() {
		try {
			out.write(buffer);
			
			System.out.println(readData(in));
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				out.close();
				in.close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	private static String readData(InputStream in) throws IOException {
		StringBuffer sb = new StringBuffer();
		int position = 0;
		byte[] buffer = new byte[10];
		
		while((position = in.read(buffer, 0, buffer.length)) != -1) {
			sb.append(new String(buffer, 0, position));
		}
		return sb.toString();
	}

}
